import React, { PureComponent,Fragment } from "react";
import { connect } from "dva";
import moment from "moment";
import router from 'umi/router';
import { Row, Col, Card, Icon, Button, message, Divider, Form, Input, Tag} from "antd";
import StandardTable from '../../../components/StandardTable';
import Authorized from '../../../utils/Authorized';

import styles from '../../Pbulic.less';
const FormItem = Form.Item;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@connect(({ notice,loading }) => ({
  resdata: notice.resdata,
  loading: notice.loading,
  // loading: loading.models.equipment_integrated,
}))
@Form.create()
export default class ListTable extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      currentPage: 1,
      pageSize: 10,
      selectedRows: [],
      formValues: {},
    };
  }

  componentWillUnmount() {

  }


  componentDidMount() {
    const { pageSize } = this.state;
    const { location, dispatch} = this.props;
    const pagesquery = location.query;

    // 列表
    this.getDataList(pagesquery,pageSize,1);


  }


  componentWillReceiveProps(nextProps) {
    // 外层发起刷新数据请求
    if ((nextProps.match.path!==this.props.match.path) || (nextProps.isReloadList === true && this.props.isReloadList === false)) {
      const { pageSize } = this.state;
      this.getDataList({},pageSize,1);
      this.props.sotpReloadList();
    }
  }


  getDataList(params,pageSize,currentPage) {
    const { dispatch, match } = this.props;
    const noticeType = match.path=="/notice/announce/list" ? "1" : match.path=="/notice/notify/list" ? "2" : "0";
    dispatch({
      type: 'notice/fetch_notice_list',
      payload: {
        pageSize,
        currentPage,
        // ...pagesquery,
        ...params,
        noticeType,
      },
    });
  }

  // 分页、排序、筛选变化时触发
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues,pageSize } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      // currentPage: pagination.current,
      // pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };

    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    this.setState({
      currentPage:pagination.current
    },()=>{
      this.getDataList(params,pageSize,pagination.current);
    })

  };

  // 重置表单
  handleFormReset = () => {
    const { form } = this.props;
    const {pageSize,currentPage} = this.state;
    // form.resetFields();
    form.setFieldsValue({
      noticeTitle:undefined,
    });
    this.setState({
      formValues: {},
    });
    this.getDataList({},pageSize,1);
  };


  // 表格复选框选中
  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows.map(item => item.noticeId),
    });
  };

  // 表单搜索
  handleSearchSubmit = e => {
    e.preventDefault();

    const { form } = this.props;
    const { pageSize } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      this.setState({
        formValues: fieldsValue,
      });

      this.getDataList(fieldsValue,pageSize,1);
    });
  };



  // 链接跳转-------------------
  handleLink = (action,detailInfoId) =>{
    const { dispatch, match } = this.props;
    const { formValues, currentPage} = this.state;
    const noticeType = match.path=="/notice/announce/list" ? "announce" : match.path=="/notice/notify/list" ? "notify" : "0";
    let linkpath;
    switch (action) {
      case 'add':
        linkpath = `/notice/${noticeType}/detail/add`;
        break;
      case 'edit':
        linkpath = `/notice/${noticeType}/${detailInfoId}/edit`;
        break;
      case 'info':
        linkpath = `/notice/${noticeType}/${detailInfoId}/info`;
        break;
      default:
        break;
    }
    router.push({ pathname:`${linkpath}`,  query: { ...formValues, currentPage} });
  }


  // 搜索内容
  renderSearchForm() {
    const { form, pagesquery } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form onSubmit={this.handleSearchSubmit} >
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="标题">
              {getFieldDecorator('noticeTitle',{
                initialValue: pagesquery && pagesquery.fileTitle ? pagesquery.fileTitle : undefined,
              })(<Input placeholder="请输入标题名称" />)}
            </FormItem>
          </Col>


          <Col md={6} sm={24}>
            <div style={{ float: 'right', marginBottom: 24 }}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </div>
          </Col>

        </Row>
      </Form>
    );
  }


  render() {

    const { resdata, loading, match } = this.props;
    const { selectedRows } = this.state;

    const noticeType = match.path=="/notice/announce/list" ? "announce" : match.path=="/notice/notify/list" ? "notify" : "0";


    const columns = [
      {
        title: '标题',
        dataIndex: 'noticeTitle',
        render: (text, row, index) => (
          <Fragment>
            {row.isTop=="01" && <Tag color="blue">置顶</Tag>}{text}
          </Fragment>
        ),
      },
      {
        title: '发布人',
        dataIndex: 'creatorName',
      },
      {
        title: '发布时间',
        dataIndex: 'createTime',
        render: text => moment(text).format("YYYY-MM-DD HH:mm")
      },
      {
        title: '操作',
        // width: 150,
        // fixed:'right',
        render: (text, row, index) => (
          <Fragment>
            <Authorized authority={noticeType==="announce" ? '10324' : noticeType==="notify" ? '10334' : '00000'} >
              <a onClick={() => this.handleLink('info',row.noticeId)}>详情</a>
              <Divider type="vertical" />
            </Authorized>
            <Authorized authority={noticeType==="announce" ? '10323' : noticeType==="notify" ? '10333' : '00000'} >
              <a onClick={() => this.handleLink('edit',row.noticeId)}>修改</a>
            </Authorized>
          </Fragment>
        ),
      },
    ];


    return (
      <Card bordered={false}>
        {
          (noticeType=="announce" || noticeType=="notify") &&
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSearchForm()}</div>

            <div className={styles.tableListOperator}>
              <Authorized authority={noticeType==="announce" ? '10322' : noticeType==="notify" ? '10332' : '00000'} >
                <Button icon="plus" type="primary"  onClick={() => this.handleLink('add',null)}>
                {noticeType=="announce" ? "发布公告" : "发布通知"}
                </Button>
              </Authorized>


            </div>

            <StandardTable
              selectedRows={selectedRows}
              rowKey="noticeId"
              // scroll={{ x: 1500 }}
              loading={loading.reslist}
              data={resdata}
              columns={columns}
              // onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />

          </div>
        }
      </Card>

    );
  }
}
